//开始之前请引入reconnecting-websocket.js
var ipRe=/^(\d+)\.(\d+)\.(\d+)\.(\d+).*$/;//正则表达式
function SxpSockJS(url){
    this.host = window.location.host;

    if(ipRe.test(url)){
        this.url = url;
    }else if(url.indexOf("http") == 0 || url.indexOf("https") == 0){
        this.url = url.splice("//")[1];
    }else{
        this.url = this.host + url;
    }
    console.log("connection url:"+this.url);
    this.websocket = null;
    this.subscribe = function(theme, callBack){//theme订阅主题，callBack回调函数
        this.websocket.themeMap[theme] = callBack;
        this.websocket.send("{theme:'"+theme+"',option:'registerTheme'}");
    };
    this.connect = function(onOpen,onError){
        this.websocket = new ReconnectingWebSocket("ws://"+this.url,null,{reconnectInterval: 3000});
        this.websocket.themeMap = {};
        this.websocket.timeoutInterval = 5400;
        this.websocket.onopen = function(event){
            console.log("漂亮!与服务器websocket连接成功!!!");
            if(onOpen && typeof onOpen === "function")onOpen();
        };
        this.websocket.onclose = function(event){
            console.log("悲剧!与服务器websocket连接断开!!!");
            console.log('websocket 断开: ' + event.code + ' ' + event.reason + ' ' + event.wasClean)
            if(onError && typeof onOpen === "function")onError();
        };
        this.websocket.onmessage = function (data) {
            console.log(data.timeStamp+"<<< CONNECTED");
            var obj = eval('(' + data.data + ')');
            var callBack = this.themeMap[obj.theme];
            if(callBack){
                console.log("theme:"+obj.theme);
                console.log("jsonData:"+obj.body);
                callBack(obj);
            }
            console.log(data.timeStamp+"<<< END");
            console.log(" ");
        }
    }
}